package com.libraryApp.controller;

import com.libraryApp.appCommon.Constants;
import com.libraryApp.appCommon.ServiceResultEnum;
import com.libraryApp.appUtil.*;
import com.libraryApp.appVo.AppUserInfoVo;
import com.libraryApp.appVo.UserLoginVo;
import com.libraryApp.entity.UserDo;
import com.libraryApp.service.appLoginService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @CreateDate 2021-03-06
 * @Author yufang
 */
@Api(tags={"用户登录接口"})
@RestController
@CrossOrigin
@RequestMapping("app/user")
public class appLoginController {

    @Autowired
    appLoginService appLoginService;

    @ApiOperation("用户登录接口")
    @ApiResponses({
            @ApiResponse(code=0, message="成功"),
            @ApiResponse(code=500, message="系统异常"),
            @ApiResponse(code=999, message="未登录"),
            @ApiResponse(code=1000, message="数据有效性检查不通过"),
            @ApiResponse(code=1001, message="业务规则检查不通过")
    })
    @RequestMapping(value = "/login" , method = RequestMethod.POST)
    public Result<String> appLogin(@RequestBody UserLoginVo vo){

        if (!NumberUtil.isPhone(vo.getLoginName())){
            return ResultGenerator.genFailResult(ServiceResultEnum.LOGIN_NAME_IS_NOT_PHONE.getResult());
        }
        String loginResult = appLoginService.login(vo);

//        logger.info("login api,loginName={},loginResult={}", vo.getLoginName(), loginResult);

        //登录成功
        if (!StringUtils.isEmpty(loginResult) && loginResult.length() == Constants.TOKEN_LENGTH) {
            Result result = ResultGenerator.genSuccessResult();
            result.setData(loginResult);
            return result;
        }
        //登录失败
        return ResultGenerator.genFailResult(loginResult);

    }

    @ApiOperation("获取用户信息接口")
    @ApiResponses({
            @ApiResponse(code=0, message="成功"),
            @ApiResponse(code=500, message="系统异常"),
            @ApiResponse(code=999, message="未登录"),
            @ApiResponse(code=1000, message="数据有效性检查不通过"),
            @ApiResponse(code=1001, message="业务规则检查不通过")
    })
    @RequestMapping(value = "/info" , method = RequestMethod.GET)
    public Result<String> getUserInfo(@TokenToUser UserDo userDo){

        //已登录则直接返回
        if(userDo == null){
            Result<String> res = new Result<>();
            res.setResultCode(416);
            res.setData("登录信息过期");
            res.setMessage("登录信息过期");
            return res;
        }

        AppUserInfoVo vo = new AppUserInfoVo();
        BeanUtil.copyProperties(userDo, vo);
        return ResultGenerator.genSuccessResult(vo);

    }

}
